package cn.zurish.cloud.security.config;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
    // 自定义登录成功处理器
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.
                authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/ajaxLogin").permitAll() //ajax登陆页不需要认证
                        .anyRequest().authenticated()
                )
                .formLogin(form -> form
                                .loginPage("/login") // 自定义登录页路径
//                        .defaultSuccessUrl("/", true)        // 登录成功后跳转路径
//                        .failureUrl("/login?error=true")         // 登录失败后跳转路径
                                .successHandler(loginSuccessHandler())
                                .failureHandler(loginFailureHandler())
                                .permitAll() //不需要对login认证
                )
                .logout(withDefaults())
                .csrf(csrf -> csrf.disable()) //关闭csrf防护
        ;
        return http.build();
    }

    // 自定义登录成功处理器
    @Bean
    public AuthenticationSuccessHandler loginSuccessHandler() {
        return (request, response, authentication) -> {
            if (isAjaxRequest(request)) {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"code\":200, \"message\":\"/认证成功\"}");
            } else {
                response.sendRedirect("/");
            }
        };
    }

    // 自定义登录失败处理器
    @Bean
    public AuthenticationFailureHandler loginFailureHandler() {
        return (request, response, exception) -> {
            if (isAjaxRequest(request)) {
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"code\":401, \"message\":\"认证失败\"}");
            } else {
                response.sendRedirect("/login?error=true");
            }
        };
    }

    //判断是否ajax请求
    public boolean isAjaxRequest(HttpServletRequest request) {
        String xRequestedWith = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(xRequestedWith);
    }

}